package com.mmcb.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;


import com.mmcb.config.OssProperties;
import com.mmcb.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 作者：李嘉浩
 * 时间：2024-08-28-20:16
 * 功能：
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private OssProperties ossProperties;
    @Override
    public String upload(InputStream inputStream, String originalFilename,String module) throws ClientException, IOException {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ossProperties.getEndpoing();

        // 填写Bucket名称，例如examplebucket。
        String bucketName = ossProperties.getBucketName();

        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        //文件夹
        String format = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));  // 文件夹
        //文件名
        String uuid= UUID.randomUUID().toString();
        //文件后缀
        String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));
        //模块名
        String  method=module;
        //完整文件名
        String objectName = method+"/"+ format+"/"+uuid+suffix;

        String accessKey = ossProperties.getAccessKey();
        String accessSecret = ossProperties.getAccessSecret();


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey,accessSecret);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
            // ossClient.putObject();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "http://"+bucketName+"."+endpoint+"/"+objectName;
    }

    @Override
    public void remove(String url) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ossProperties.getEndpoing();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ossProperties.getBucketName();
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = url.replace("http://"+bucketName+"."+endpoint+"/","");

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, ossProperties.getAccessKey(),ossProperties.getAccessSecret());

        try {
            // 删除文件。
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
